//
//  ViewController.m
//  气泡聊天Demo
//
//  Created by 米华 on 16/7/11.
//  Copyright © 2016年 Apon. All rights reserved.
//

#import "ViewController.h"
#import "CellOfChat.h"
#import "ModelOfChat.h"
#import "ViewOfInput.h"
@interface ViewController () <UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrOfChat;
@property (nonatomic, strong) ViewOfInput *inputView;
@end

static NSString *identify = @"CellOfChat";

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //根据按所在界面的status bar，navigationbar，与tabbar的高度，自动调整scrollview的 inset,设置为no，不让viewController调整，我们自己修改布局
    self.automaticallyAdjustsScrollViewInsets = NO;
    
//    self.arrOfChat = @[@"1",@"2",@"3",@"4",@"5"].mutableCopy;
    
    [self createTableView];
    
    [self createInputView];
}


#pragma mark - 创建数组懒加载方法
- (NSMutableArray *)arrOfChat {
    
    if (_arrOfChat == nil) {
        
        _arrOfChat = [[NSMutableArray alloc] init];
        
    }
    
    return _arrOfChat;
}


#pragma mark - create tableView
- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 100) style:UITableViewStylePlain];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    self.tableView.delegate = self;
    
    self.tableView.dataSource = self;
    
    // 消除TableView横线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    // 小技巧, 使用后不会出现未规定的多余cell
    UIView *view = [[UIView alloc] init];
    
    self.tableView.tableFooterView = view;
    
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[CellOfChat class] forCellReuseIdentifier:identify];
    
}

#pragma mark - createInputView
- (void)createInputView {
    self.inputView = [[ViewOfInput alloc] init];
    
    self.inputView.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50);
    
    self.inputView.backgroundColor = [UIColor colorWithRed:0.91 green:0.90 blue:0.91 alpha:1.00];
    
    self.inputView.textView.delegate = self;
    
    [self.inputView.buttonOfSend addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.inputView];
    
    //注册键盘的通知:显隐性质 此时需要调用will的方法使输入栏与键盘的弹出回收保持同时进行
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    
    // 添加点击收回键盘的手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Click:)];
    
    [self.view addGestureRecognizer:tap];
    
}

- (void)Click:(UITapGestureRecognizer *)tap {
    
    [self.view endEditing:YES];
    
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    
    [self.view endEditing:YES];
    
    return YES;
    
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        
        [self sendMessage];
        
        return NO;
    }
    return YES;
}

#pragma mark - 监听键盘弹出
- (void)keyboardShow:(NSNotification *)noti {
    
    // 取得键盘frame信息
    CGRect rect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    NSLog(@"%@", NSStringFromCGRect(rect));
    
    // 如果判断结果小于,则说明输入框被遮挡
    if ([UIScreen mainScreen].bounds.size.height - rect.size.height < self.inputView.frame.origin.y + self.inputView.frame.size.height) {
        
        
        CGRect tempRect = self.view.frame;
        
        tempRect.origin.y = - (rect.size.height);
        
        self.view.frame = tempRect;
        
    }
    
    // 可见范围缩小后, TableView的frame也要随之变化
    self.tableView.frame = CGRectMake(0, rect.size.height + self.inputView.frame.size.height, self.view.frame.size.width, 667 - 30 - rect.size.height);
    
    if (self.arrOfChat.count != 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.arrOfChat.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
}

- (void)keyboardHide:(NSNotification *)noti {
    self.view.frame = [UIScreen mainScreen].bounds;
    self.tableView.frame = [UIScreen mainScreen].bounds;
}


#pragma mark - 发送按钮点击事件
- (void)sendMessage {
    
    NSLog(@"点击了");
    
    if (![self.inputView.textView.text isEqualToString:@""]) {
        ModelOfChat *chatModel = [[ModelOfChat alloc] init];
        
        chatModel.message = self.inputView.textView.text;
        
        [self.arrOfChat addObject:chatModel];
    }
    
    [self.tableView reloadData];
    
    // tableView 滚至底部的方法
    if (self.arrOfChat.count != 0) {
        
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.arrOfChat.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        
    }
    
    self.inputView.textView.text = @"";
    
    
}

#pragma mark - tableViewDataSource 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrOfChat.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CellOfChat *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[CellOfChat alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    
    [cell ChatCellCommentWithModel:self.arrOfChat[indexPath.row]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelOfChat *model = [self.arrOfChat objectAtIndex:indexPath.row];
    
    CGRect rect = [model.message boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    
    return rect.size.height + 45;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
